import dotenv from "dotenv";
import Koa from "koa";
import { koaBody } from "koa-body";
import Router from "@koa/router";
import Handlebars from "handlebars";
import fs from "fs/promises";
import path from "path";
import {
  pidFile,
  restartMySQL,
  startMySQL,
  statusTextMySQL,
  stopMySQL,
} from "./mysql";
import { isFile } from "./file";

dotenv.config();

const app = new Koa();

const router = new Router();

router.get("/", async (ctx, next) => {
  ctx.response.set("Content-Type", "text/html; charset=utf-8");
  const viewContent = await fs.readFile(
    path.join(__dirname, "../views/index.html"),
    "utf-8"
  );
  const tpl = Handlebars.compile(viewContent);
  const statusText = await statusTextMySQL();
  ctx.response.body = tpl({ statusTextMySQL: statusText });
});

router.get("/mysql/status", async (ctx, next) => {
  const statusText = await statusTextMySQL();
  ctx.response.body = { statusText };
});

router.post("/mysql", async (ctx, next) => {
  const { type } = ctx.request.body;
  let statusText = "";
  if (!type) {
    ctx.response.body = { statusText };
    return;
  }

  try {
    if (type === "start") {
      await startMySQL();
      statusText = "(已开启)";
    } else if (type === "stop") {
      await stopMySQL();
      statusText = "(已停止)";
    }
  } catch (err) {
    statusText = `(${err.message})`;
  }

  ctx.response.body = { statusText };
});

// koaBody.json = true，默认是开启 application/json 正文解析的
app.use(koaBody()).use(router.routes()).use(router.allowedMethods());

app.listen(5555);

console.log(`🚀  Server ready at: http://localhost:5555`);
